package com.gxjc.action;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.codehaus.jackson.map.ObjectMapper;

import com.gxjc.model.Node;
import com.gxjc.service.NodeService;
import com.opensymphony.xwork2.ActionSupport;

public class NodeAction extends ActionSupport {
	@Resource
	NodeService nodeService;
	public String name;
	public Integer homeId;
	public String tojsp;
	//public String nodeJson;
	public List<Node> list = new ArrayList<>();
	public String getAll(){
		list = nodeService.getAll();
		return "success";
	}
	public String add(){
		Node node = new Node();
		node.setName(name);
		nodeService.save(node);
		tojsp = "addNode.jsp";
		return SUCCESS;
	}
	public void getNodeByHomeId(){
		List<Node> nodes = nodeService.getNodeBySql("from Node as n where n.home.id="+homeId);
		List<Node> delHomeNodes = new ArrayList<>();
		for (int i = 0; i < nodes.size(); i++) {
			Node n = nodes.get(i);
			n.setHome(null);
			n.setNodeDatas(null);
			delHomeNodes.add(n);
		}
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			HttpServletResponse response=ServletActionContext.getResponse();
			response.setContentType("text/html;charset=UTF-8");
			String nodeJson = objectMapper.writeValueAsString(delHomeNodes);
			PrintWriter out = response.getWriter();
			out.print(nodeJson);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getTojsp() {
		return tojsp;
	}
	public void setTojsp(String tojsp) {
		this.tojsp = tojsp;
	}
	public List<Node> getList() {
		return list;
	}
	public void setList(List<Node> list) {
		this.list = list;
	}
	public Integer getHomeId() {
		return homeId;
	}
	public void setHomeId(Integer homeId) {
		this.homeId = homeId;
	}	
}
